const mutations = {
    // 设置token
    SET_TOKEN(state, token) {
        state.token = token;
        state.isLogin = !!token;
        if (token) {
            uni.setStorageSync('token', token);
        } else {
            uni.removeStorageSync('token');
        }
    },
    
    // 设置用户信息
    SET_USER_INFO(state, userInfo) {
        state.userInfo = userInfo;
        state.isLogin = true;
        if (userInfo && Object.keys(userInfo).length > 0) {
            uni.setStorageSync('userInfo', userInfo);
        } else {
            uni.removeStorageSync('userInfo');
        }
    },
    
    // 登录
    LOGIN(state, { token, userInfo }) {
        state.token = token;
        state.userInfo = userInfo;
        state.isLogin = true;
        
        // 持久化存储
        uni.setStorageSync('token', token);
        uni.setStorageSync('userInfo', userInfo);
    },
    
    // 登出
    LOGOUT(state) {
        state.token = '';
        state.userInfo = {};
        state.isLogin = false;
        
        // 清除存储
        uni.removeStorageSync('token');
        uni.removeStorageSync('userInfo');
        
        // 清空地址数据
        this.commit('CLEAR_ADDRESS_DATA');
    },

    // 设置手机号
    SET_PHONE(state, phone) {
        state.phone = phone;
    },

    // 控制优惠券弹窗显示状态（并持久化“不再显示”标记）
    SET_COUPON_SHOW(state, show) {
        state.couponShow = !!show
        if (!show) {
            state.couponShownFlag = true
        }
    },
    
    // 设置登录后返回路径（不持久化）
    SET_REDIRECT_AFTER_LOGIN(state, path) {
        state.redirectAfterLogin = path || ''
    },
    CLEAR_REDIRECT_AFTER_LOGIN(state) {
        state.redirectAfterLogin = ''
    },
    
    // 设置选中师傅（不持久化）
    SET_SELECTED_MASTER(state, master) {
        state.selectedMaster = master || null
    },
    
    // 设置预约信息（不持久化）
    SET_RESERVATION(state, payload) {
        const value = payload && (payload.date || payload.time) ? payload : { date: '', time: '' }
        state.reservation = value
    },
    
    // 设置选中规格（不持久化）
    SET_SELECTED_SPEC(state, spec) {
        state.selectedSpec = spec || null
    },
    
    // 清空订单选择（不持久化）
    CLEAR_ORDER_SELECTION(state) {
        state.selectedMaster = null
        state.reservation = { date: '', time: '' }
        state.selectedSpec = null
    },
    
    // 地址相关，仅保留当前选中地址（不持久化）
    SET_SELECTED_ADDRESS(state, address) {
        state.selectedAddress = address;
    },
    
    // 设置地址列表
    SET_ADDRESS_LIST(state, addressList) {
        // 确保所有地址的ID和默认状态都是正确的类型
        const normalizedAddressList = addressList.map(address => ({
            ...address,
            id: Number(address.id),
            isDefault: Number(address.isDefault)
        }));
        
        state.addressList = normalizedAddressList;
        uni.setStorageSync('addressList', normalizedAddressList);
        
        // 重置默认地址ID
        state.defaultAddressId = null;
        uni.removeStorageSync('defaultAddressId');
        
        // 只有当地址列表中确实有标记为默认的地址时，才设置默认地址ID
        const defaultAddress = normalizedAddressList.find(item => item.isDefault === 1);
        if (defaultAddress) {
            state.defaultAddressId = defaultAddress.id;
            uni.setStorageSync('defaultAddressId', defaultAddress.id);
        } else {
        }
    },
    
    // 添加地址
    ADD_ADDRESS(state, address) {
        // 确保ID类型一致
        const addressWithNumericId = {
            ...address,
            id: Number(address.id),
            isDefault: Number(address.isDefault)
        };
        
        state.addressList.push(addressWithNumericId);
        uni.setStorageSync('addressList', state.addressList);
        
        // 如果添加的是默认地址，设置默认地址ID
        if (addressWithNumericId.isDefault === 1) {
            state.defaultAddressId = addressWithNumericId.id;
            uni.setStorageSync('defaultAddressId', addressWithNumericId.id);
        }
    },
    
    // 更新地址
    UPDATE_ADDRESS(state, { id, address }) {
        // 确保ID类型一致（转换为数字进行比较）
        const numericId = Number(id)
        const index = state.addressList.findIndex(item => Number(item.id) === numericId);
        if (index !== -1) {
            // 保留原有的ID，确保类型一致
            const updatedAddress = { 
                ...state.addressList[index], 
                ...address,
                id: state.addressList[index].id // 保持原有ID类型
            };
            state.addressList[index] = updatedAddress;
            uni.setStorageSync('addressList', state.addressList);
            
            // 如果更新的是默认地址，同步更新默认地址ID
            if (updatedAddress.isDefault === 1) {
                state.defaultAddressId = updatedAddress.id;
                uni.setStorageSync('defaultAddressId', updatedAddress.id);
            }
        }
    },
    
    // 删除地址
    DELETE_ADDRESS(state, id) {
        const numericId = Number(id)
        state.addressList = state.addressList.filter(item => Number(item.id) !== numericId);
        uni.setStorageSync('addressList', state.addressList);
        
        // 如果删除的是默认地址，清空默认地址ID
        if (Number(state.defaultAddressId) === numericId) {
            state.defaultAddressId = null;
            uni.removeStorageSync('defaultAddressId');
        }
        
        // 如果删除的是当前选中的地址，清空选中状态
        if (state.selectedAddress && Number(state.selectedAddress.id) === numericId) {
            state.selectedAddress = null;
        }
    },
    
    // 设置默认地址
    SET_DEFAULT_ADDRESS(state, id) {
        const numericId = Number(id)
        
        // 先取消所有地址的默认状态
        state.addressList.forEach(item => {
            item.isDefault = 0;
        });
        
        // 设置新的默认地址
        const targetAddress = state.addressList.find(item => Number(item.id) === numericId);
        if (targetAddress) {
            targetAddress.isDefault = 1;
            state.defaultAddressId = targetAddress.id; // 保持原有ID类型
            uni.setStorageSync('addressList', state.addressList);
            uni.setStorageSync('defaultAddressId', targetAddress.id);
        }
    },
    
    // 清空地址数据（登出时使用）
    CLEAR_ADDRESS_DATA(state) {
        state.addressList = [];
        state.defaultAddressId = null;
        state.selectedAddress = null;
        uni.removeStorageSync('addressList');
        uni.removeStorageSync('defaultAddressId');
    },

    GET_ADDRESS_URL(state, url) {
        state.addressUrl = url
    },

    // 设置/更新活动同步数据（不持久化）
    SET_ACTIVITY_SYNC(state, payload) {
        // payload: { id, is_collected, is_registered }
        state.activitySync = payload || null
    },

    // 设置闲置下单商品信息（不持久化）
    SET_IDLE_ORDER_ITEM(state, payload) {
        state.idleOrderItem = payload || null
    },
    // 清空闲置下单商品信息
    CLEAR_IDLE_ORDER_ITEM(state) {
        state.idleOrderItem = null
    },
    
    // 小区选择相关 mutations
    // 设置当前城市 { province, city }
    SET_SELECTED_CITY(state, payload) {
        const value = payload && typeof payload === 'object'
            ? { province: payload.province || '', city: payload.city || '' }
            : { province: '', city: String(payload || '') } // 兼容旧调用
        state.selectedCity = value
    },
    
    // 设置小区列表
    SET_COMMUNITY_LIST(state, list) {
        state.communityList = list || []
    },
    
    // 设置选中的取货小区
    SET_SELECTED_PICKUP_COMMUNITY(state, community) {
        state.selectedPickupCommunity = community
    },
    
    // 设置选中的送货小区
    SET_SELECTED_DELIVERY_COMMUNITY(state, community) {
        state.selectedDeliveryCommunity = community
    },
    
    // 设置小区选择类型
    SET_COMMUNITY_SELECT_TYPE(state, type) {
        state.communitySelectType = type || ''
    },
    
    // 清空小区选择数据
    CLEAR_COMMUNITY_SELECTION(state) {
        state.selectedPickupCommunity = null
        state.selectedDeliveryCommunity = null
        state.communitySelectType = ''
    }
    ,
    // 设置逆地理编码的地址组件（不持久化）
    SET_ADDRESS_COMPONENT(state, payload) {
        state.addressComponent = payload || null
    }
}

export default mutations;